package com.tjhzzx.danfossNiagaraCore.util;

import org.apache.commons.lang3.StringUtils;

import javax.baja.file.BFileSystem;
import javax.baja.file.FilePath;
import javax.baja.naming.BOrd;
import javax.baja.naming.OrdQuery;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class TlsUtil {

    private static final Logger LOGGER = Logger.getLogger(TlsUtil.class.getName());
    private static final String DEFAULT_DATETIME_STRING = "2000-01-01 00:00:00";
    private static final String DEFAULT_DATE_STRING = "2000-01-01";

    public static String utilDate2String(Date date, String format, boolean bDefaultDateShowNull) {
        DateFormat sdf = new SimpleDateFormat(format);
        String dateStr = sdf.format(date);
        if (bDefaultDateShowNull && (dateStr.equals(DEFAULT_DATETIME_STRING) || dateStr.equals(DEFAULT_DATE_STRING))) {
            return "";
        }
        return dateStr;
    }

    public static String utilDate2String(Date date, boolean bDefaultDateShowNull) {
        return utilDate2String(date, "yyyy-MM-dd HH:mm:ss", bDefaultDateShowNull);
    }

    public static Date string2utilDate(String value, String format) throws ParseException {
        DateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(value);
    }

    public static Date string2utilDate(String value) throws ParseException {
        return string2utilDate(value, "yyyy-MM-dd HH:mm:ss");
    }

    public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
        long start = System.currentTimeMillis();
        if(zipFile == null){
            LOGGER.info("压缩包文件名为空！");
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
            LOGGER.info("压缩包文件名异常，zipFile={}" + zipFile.getPath());
            return;
        }
        ZipOutputStream zos = null;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[4096];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
//                out.close();
            }
            long end = System.currentTimeMillis();
            LOGGER.info("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            LOGGER.info("ZipUtil toZip exception");
            throw new RuntimeException("zipFile error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    LOGGER.info("ZipUtil toZip close exception");
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    LOGGER.info("ZipUtil toZip close exception");
                }
            }
        }
    }

    public static String buildStationHomeAbsolutePath(String path) {
        if(StringUtils.isBlank(path)) {
            LOGGER.log(Level.SEVERE, path + " is not found.");
            return null;
        }
        BOrd fileOrd = BOrd.make(path);
        OrdQuery[] queries = fileOrd.parse();
        FilePath filePath = (FilePath) queries[queries.length - 1];
        File dir = BFileSystem.INSTANCE.pathToLocalFile(filePath);
        return dir.getAbsolutePath() + "/";
    }

    public static Date getLastDate(Date date, int type, int amount) {
        Date result = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        if (type == 0) {
            calendar.add(Calendar.DATE, amount);
            result = calendar.getTime();
        } else if (type == 1) {
            calendar.add(Calendar.MONTH, amount);
            result = calendar.getTime();
        } else if (type == 2) {
            calendar.add(Calendar.YEAR, amount);
            result = calendar.getTime();
        }
        return result;
    }


    public static Date getFirstMonthDay(Date dt) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(dt);
        ca.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        ca.set(Calendar.HOUR, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        return ca.getTime();
    }

    public static Date getFirstYearDay(Date dt) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(dt);
        ca.set(Calendar.DAY_OF_YEAR, 1);//设置为1号,当前日期既为本月第一天
        ca.set(Calendar.HOUR, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);
        return ca.getTime();
    }
}
